package com.efounder.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import androidx.appcompat.app.AlertDialog;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.FragmentContainActivity;
import com.efounder.chat.activity.AddPublicFriendInfoActivity;
import com.efounder.chat.activity.SetWorkGroupActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.manager.ChatListManager;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.BadgeView;
import com.efounder.chat.zxing.qrcode.MipcaActivityCapture;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.activity.EFAppAccountMainActivity;
import com.efounder.frame.utils.Constants;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.ospmobilelib.R;
import com.efounder.util.AbFragmentManager;
import com.efounder.utils.JfResourceUtil;
import com.pansoft.resmanager.ResFileManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

/**
 * 专门为应用模块写的gridview；
 */

public class CommonGridView extends GridView {

    private static final int GRIDVIEW_COUNT = 4;// 声明每一页皮肤的个数
    private String viewType = null;
    private Hashtable menuTable;
    //是否为群应用的标记
    private String workApp;
    private String workGroup;

    private Context context;// 上下文
    private ArrayList<StubObject> viewList = new ArrayList<StubObject>();// Activity传来的数据源
    private List<View> animationList = new ArrayList<View>();
    private List<RelativeLayout> delList = new ArrayList<RelativeLayout>();

    private CommonGridAdapter adapter;
    private boolean isAnim = false;
    private String title;
//    private ImageLoader imageLoader;
//    private DisplayImageOptions options;


    public CommonGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        this.setNumColumns(GRIDVIEW_COUNT);
        //initImageLoader();
        initAdapter();
    }


    public CommonGridView(Context context, AttributeSet attrs, String title) {
        super(context, attrs);
        this.context = context;
        this.title = title;
        this.setNumColumns(GRIDVIEW_COUNT);
        // initImageLoader();
        initAdapter();
    }

//    private void initImageLoader() {
//        imageLoader = ImageLoader.getInstance();
//        options = ImageUtil.getImageLoaderOptions(R.drawable.iframe_icon_refresh);
//    }


    // 为每个单元设置数据
    private class CommonGridAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater skinInflater;

        private CommonGridAdapter(Context context) {
            this.mContext = context;
            skinInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {

            int size = (viewList == null ? 0 : viewList.size());
            return size;
        }

        @Override
        public Object getItem(int position) {
            return viewList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // 这里本来return的是position
            return position;
        }

        @SuppressLint("NewApi")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final int nowPosition = position;
            ViewHolder holder;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            } else {
                // 加载布局生成布局对象，然后取得布局中的控件，为控件设置内容
                convertView = skinInflater.inflate(
                        R.layout.viewpager_bottomgrid_item, null);
                holder = new ViewHolder();
                holder.name = (TextView) convertView
                        .findViewById(R.id.skin_popup_app_name);
                holder.icon = (ImageView) convertView
                        .findViewById(R.id.skin_popup_app_icon);
                // holder.icon.requestFocus();
                holder.layout = (RelativeLayout) convertView
                        .findViewById(R.id.item_Rel);
                holder.badgeView = new BadgeView(mContext, holder.icon);
                holder.del = (ImageView) convertView.findViewById(R.id.cross_icon);
                convertView.setTag(holder);
            }
            ApplicationInfo appInfo = context.getApplicationInfo();

            String menuIcon = (String) viewList.get(nowPosition).getString(
                    "menuIcon", "");
            menuIcon = "file://" + ResFileManager.IMAGE_DIR + "/" + menuIcon;
            Bitmap bm = null;


//            imageLoader.displayImage(menuIcon, holder.icon, options);
            LXGlideImageLoader.getInstance().displayImage(mContext, holder.icon, menuIcon, R.drawable.iframe_icon_refresh, R.drawable.iframe_icon_refresh);

            holder.name.setText((String) viewList.get(nowPosition).getString(
                    "caption", ""));

            //处理角标
            holder.badgeView.setBadgeMargin(0, 0);
            holder.badgeView.setTextSize(13);
            holder.badgeView.setBadgeBackgroundColor(getResources().getColor(
                    R.color.red));

            //badgeView.setTag("badge" + MessagePosition);

            int badgeNum = (int) viewList.get(nowPosition).getInt(
                    "badgeNum", -1);
            if (badgeNum > 99) {
                holder.badgeView.setText("99+");
                holder.badgeView.setVisibility(View.VISIBLE);
                holder.badgeView.show();
            } else if (badgeNum == -1) {
//                holder.badgeView.setText(badgeNum + "");
//                holder.badgeView.hide();
            } else if (badgeNum == 0) {
                holder.badgeView.setText(" ");
                holder.badgeView.setBadgeMargin(3);
                holder.badgeView.setTextSize(9);
                holder.badgeView.setVisibility(View.VISIBLE);
                holder.badgeView.show();
            } else {
                holder.badgeView.setText(badgeNum + "");
                holder.badgeView.show();
            }

            //ShortcutBadger.applyCount(context, badgeNum);
//
            if (badgeNum < 0) {
                holder.badgeView.setVisibility(View.INVISIBLE);
            } else {
                holder.badgeView.show();
            }


            return convertView;
        }
    }

    // 定义一个类，包含需要的每个布局和控件
    static class ViewHolder {
        RelativeLayout layout;
        ImageView icon;
        TextView name;
        ImageView del;
        BadgeView badgeView;
    }

    // 接收来自Activity的list列表
    public void setArrayList(ArrayList<StubObject> list) {
        this.viewList = list;
        // 为ViewPager设置Adapter
        adapter = new CommonGridAdapter(context);
        this.setAdapter(adapter);
        // 取消点击时的黄色背景
        this.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter.notifyDataSetChanged();
    }

    public ArrayList<StubObject> getArrayList() {
        return viewList;
    }

    public void update() {
        // initAdapter();
        adapter.notifyDataSetChanged();
    }

    public void initAdapter() {


        WindowManager wm = (WindowManager) getContext().getSystemService(
                Context.WINDOW_SERVICE);

        int width = wm.getDefaultDisplay().getWidth();
        this.setColumnWidth(width / 5);


        this.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (isAnim) {
                    cleanAnim();
                    return;
                }
                // TODO Auto-generated method stub
                try {

                    AbFragmentManager ab = new AbFragmentManager(context);
                    StubObject nowStubObejct = viewList.get(position);


                    menuTable = nowStubObejct.getStubTable();
                    viewType = (String) menuTable.get("viewType");


                    if ("menuMore".equals(viewType)) {
                        if (null != settingInterface) {
                            settingInterface.click();
                        }
                    } else if ("display".equals(viewType)) {
                        ab.startActivity(nowStubObejct, 0, 0);

                    } else if ("groupApp".equals(viewType)) {
                        String userId = EnvironmentVariable.getUserID();

                        if (EnvironmentVariable.getProperty(userId + "workgroup") == null
                                || "".equals(EnvironmentVariable.getProperty(userId + "workgroup"))) {
                            new android.app.AlertDialog.Builder(context)
                                    .setMessage("您还未设置工作群,请前往设置")
                                    .setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            context.startActivity(new Intent(context, SetWorkGroupActivity.class));
                                        }
                                    }).show();
                        } else {
                            ab.startActivity(nowStubObejct, 0, 0);
                        }
                    } else if ("appacount".equals(viewType)) {
                        final User user = WeChatDBManager.getInstance().
                                getOneOfficialNumber(Integer.valueOf((String) menuTable.get("appId")));
                        if (user == null) {
                            AlertDialog dialog = new AlertDialog.Builder(context).setMessage("您还没有关注公众号，是否要关注？").setTitle(R.string.common_text_hint).setNegativeButton(R.string.common_text_cancel, null)

                                    .setPositiveButton(R.string.common_text_confirm, new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            if ((EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG") && Integer.valueOf((String) menuTable.get("appId")) == 6392) || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG") && Integer.valueOf((String) menuTable.get("appId")) == 709) {
                                                ChatListManager chatListManager = new ChatListManager();
                                                chatListManager.clearunReadCount(Integer.valueOf((String) menuTable.get("appId")), (byte) 0);
                                                EventBus.getDefault().post(new UpdateBadgeViewEvent(Integer.valueOf((String) menuTable.get("appId")) + "", (byte) 2));
                                            }

                                            Intent intent = new Intent(context,
                                                    AddPublicFriendInfoActivity.class);
                                            intent.putExtra("userID", (String) menuTable.get("appId"));
                                            context.startActivity(intent);
                                        }
                                    }).show();

                            return;
                        }
                        //跳转公众号
                        Intent intent = null;

                        intent = new Intent(context, EFAppAccountMainActivity.class);
                        intent.putExtra("id", Integer.valueOf((String) menuTable.get("appId")));
                        intent.putExtra("nickName", (String) menuTable.get("caption"));

                        if (user.getNickName().equals("任务中心") && ((EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG") && user.getId() == 6392) || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).contains("OSPMobileLiveAppTG") && user.getId() == 709)) {
                            ChatListManager chatListManager = new ChatListManager();
                            chatListManager.clearunReadCount(Integer.valueOf((String) menuTable.get("appId")), (byte) 0);
                            EventBus.getDefault().post(new UpdateBadgeViewEvent(Integer.valueOf((String) menuTable.get("appId")) + "", (byte) 2));
                        }
                        context.startActivity(intent);

                    } else if ("saoyisao".equals(viewType)) {
                        Intent intent = new Intent(context, MipcaActivityCapture.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                    } else if ("ywfw".equals(viewType)) {
                        Intent intent = new Intent(context, Class.forName("com.efounder.RNCWGXActivity"));
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        context.startActivity(intent);
                    } else if ("video".equals(viewType)) {//视频监控
                        Intent intent = new Intent(context,
                                Class.forName("com.efounder.zhongyuan.activity.VedioDetail4Activity"));
                        intent.putExtra("type", viewList.get(position));
                        context.startActivity(intent);
                    } else {
                        Intent intent = new Intent(context,
                                FragmentContainActivity.class);
                        intent.putExtra("type", viewList.get(position));
                        context.startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

        });

        CommonGridAdapter adapter = new CommonGridAdapter(context);
        this.setAdapter(adapter);
        // 取消点击时的黄色背景
        this.setSelector(new ColorDrawable(Color.TRANSPARENT));
        adapter.notifyDataSetChanged();
        //allViews.add(this);
    }

    private void cleanAnim() {
        isAnim = false;
        for (int j = 0; j < animationList.size(); j++) {
            animationList.get(j).clearAnimation();
            delList.get(j).setVisibility(View.INVISIBLE);
        }
    }

    // * 文件保存成功后发送广播

    public void sendBroadCast(int i) {

        String ACTION = "uiChange";
        Intent intent = new Intent();
        if (i == 0) {
            intent.putExtra("name", "button0");
        } else if (i == 1) {
            intent.putExtra("name", "button0-");
        } else {
            intent.putExtra("name", "del");
        }
        intent.setAction(ACTION);
        // 普通广播
        context.sendBroadcast(intent);
    }


    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,

                MeasureSpec.AT_MOST);

        super.onMeasure(widthMeasureSpec, expandSpec);

    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        View localView1 = getChildAt(0);
        int column = getWidth() / localView1.getWidth();
        int childCount = getChildCount();
        Paint localPaint;
        localPaint = new Paint();
        localPaint.setStyle(Paint.Style.STROKE);
//        localPaint.setColor(getContext().getResources().getColor(
//                R.color.divide_line_color));
        localPaint.setColor(JfResourceUtil.getSkinColor(R.color.divide_line_color));

        for (int i = 0; i < childCount; i++) {
            View cellView = getChildAt(i);
            if ((i + 1) % column == 0) {
                canvas.drawLine(cellView.getLeft(), cellView.getBottom(),
                        cellView.getRight(), cellView.getBottom(), localPaint);
            } else if ((i + 1) > (childCount - (childCount % column))) {
                canvas.drawLine(cellView.getRight(), cellView.getTop(),
                        cellView.getRight(), cellView.getBottom(), localPaint);
            } else {
                canvas.drawLine(cellView.getRight(), cellView.getTop(),
                        cellView.getRight(), cellView.getBottom(), localPaint);
                canvas.drawLine(cellView.getLeft(), cellView.getBottom(),
                        cellView.getRight(), cellView.getBottom(), localPaint);
            }
        }
//        if (childCount % column != 0) {
//            for (int j = 0; j < (column - childCount % column); j++) {
//                View lastView = getChildAt(childCount - 1);
//                //画同一行空白的竖线
//                canvas.drawLine(lastView.getRight() + lastView.getWidth() * j,
//                        lastView.getTop(),
//                        lastView.getRight() + lastView.getWidth() * j,
//                        lastView.getBottom(), localPaint);
//                //画同一行空白的横向
//                canvas.drawLine(lastView.getLeft() + lastView.getWidth() * (j),
//                        lastView.getBottom(),
//                        lastView.getRight() + lastView.getWidth() * (j ),
//                        lastView.getBottom(), localPaint);
//            }
//        }
    }

    public interface SettingInterface {
        public void click();
    }

    public SettingInterface getSettingInterface() {
        return settingInterface;
    }

    public void setSettingInterface(SettingInterface settingInterface) {
        this.settingInterface = settingInterface;
    }

    /*全选回调*/
    SettingInterface settingInterface = null;
}
